<!DOCTYPE html>
<html>
<head>
    <title>预约</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport"
          content="width=device-width,height=device-height,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    <meta name="format-detection" content="telephone=no"/>
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="css/weui.css"/>
    <link rel="stylesheet" href="css/example.css"/>
    <link rel="stylesheet" href="css/jquery-weui.css">
    <script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <style>
        ul {
            list-style: none;
            border-bottom: 1px solid #e8e8e8;
        }

        li {
            margin: 0px;
            padding: 0px;
            height: 123px;
            padding: 0px;
            border-bottom: 1px solid #ffffff;
            background-color: white;
            display: block;
            zoom: 1;
        }

        #gotop div {
            position: absolute;
            margin: auto;
            right: 0px;
            left: 0px;
        }

        .name1 {
            float: left;
            width: 45%;
        }

        .name2 {
            float: right;
            width: 55%;
        }

        .weui-input {
            padding: 10px 15px;
        }

        .weui-select {
            line-height: 1.47058824;
            height: 1.47058824em;
        }
    </style>
</head>
<body>

<div class="weui-navbar">
    <div class="weui-navbar__item weui_bar__item_on" style="font-size: 20px">
        请填写预约详情
    </div>
</div>
<div style="margin-top:60px ">
    <div class="weui-cells weui-cells_form">
        <div id="abnormity">
            <div class="weui-cells weui-cells_radio">

                <div class="weui-panel weui-panel_access">

                    <div class="weui-panel__hd">屠宰类型</div>
                    <div id="libiao">

                    </div>

                </div>
            </div>
        </div>

        <div class="weui-cell">
            <div class="weui-cell__hd"><label for="" class="weui-label">时间</label></div>
            <div class="weui-cell__bd" style="width: 40%">
                <input id="time" class="weui-input" type="date">
            </div>
            <div class="weui-cell__bd">
                <select class="weui-select" id="select1" name="select1" onblur="selectTime()">
                    <option selected="" value="00:00">00:00-3:00</option>
                    <option value="3:00">3:00-6:00</option>
                    <option value="6:00">6:00-9:00</option>
                    <option value="9:00">9:00-12:00</option>
                    <option value="12:00">12:00-15:00</option>
                    <option value="15:00">15:00-18:00</option>
                    <option value="18:00">18:00-21:00</option>
                    <option value="21:00">21:00-00:00</option>
                </select>
            </div>
        </div>
    </div>

    <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
            <div class="weui-cell__bd">
                <div class="weui-uploader">
                    <div class="weui-uploader__hd">
                        <p class="weui-uploader__title">检疫证明</p>
                        <div class="weui-uploader__info"></div>
                    </div>
                    <div class="weui-uploader__bd">
                        <ul class="weui-uploader__files" id="uploaderFiles">

                        </ul>
                        <div class="weui-uploader__input-box" id="showPicker">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- loading toast -->
    <div id="loadingToast" style="display: none;">
        <div class="weui-mask_transparent"></div>
        <div class="weui-toast">
            <i class="weui-loading weui-icon_toast"></i>
            <p class="weui-toast__content">数据加载中</p>
        </div>
    </div>

    <a href="javascript:;" class="weui-btn weui-btn_primary" id="subscribe">预约</a>
</div>
</body>
<script src="../../js/jquery-1.7.2.min.js"></script>
<script src="../../js/jquery-weui.js"></script>
<script src="../singleton.js"></script>
<script>
    /*/!**
     * 获取微信接口标识
     *!/
    /!**
     * 当前页面url
     * @type {string}
     *!/
    sign_URL = document.location.toString();
    var check_id=Math.random().toString(36).substr(2);
    $.ajax({
        url: "../../wechat/sign.do",
        async: false,
        type: "GET",
        data: {
            campusId: 1,
            url: sign_URL
        },success: function (data) {
            var da = data;
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: da.appid, // 必填，公众号的唯一标识
                timestamp: da.timeStamp, // 必填，生成签名的时间戳
                nonceStr: da.nonceStr, // 必填，生成签名的随机串
                signature: da.signature,// 必填，签名，见附录1
                jsApiList: ["chooseImage", "uploadImage", "downloadImage"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(function () {
                //alert("wx.config success.");
                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
            });
            wx.error(function (res) {
                alert("wx.config failed.");
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，
                // 也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            });
        }
    })
    var photoSize="";
    var images = {
        localId: [],// 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
        serverId: []// 返回图片的服务器端ID
    };
    function chooseImage() {
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                images.localId = res.localIds;// 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                console.log('已选择 ' + res.localIds.length + ' 张图片');
                photoSize = images.localId.length;
                images.serverId = [];
                for (var i=0;i<photoSize;i++){
                    var localIdi = images.localId[i];
                    uploadImage(localIdi)
                }
            }
        });
    }

    function uploadImage(localIdi) {
        wx.uploadImage({
            localId: localIdi, // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
                images.serverId = res.serverId; // 返回图片的服务器端ID
                alert("成功");
                wxImgCallback()
            },
            fail: function (res) {
                console.log(res);
            }
        });
    }
    function wxImgCallback(abattoir, imagename, serverId) {
        console.log("serverId=" + serverId);
        //将serverId传给wx_upload.php的upload方法
        var url = "/shambles/mobile/booth/fileUpload.do";
        $.get(url, {
            campusId: 1,
            imagename: imagename,
            serverId: serverId,
            id: abattoir,
        }, function (data) {
            console.log(data);
            if (data == 0) {
                alert("上传图片失败!");
                console.log(data.msg);
            } else if (data == 1) {
                //存储到服务器成功后的处理
                alert("上传图片" + name + "成功!");

                var html = "<li class='weui-uploader__file' style='background-image:url(../../img/mobileRight.jpg)'></li>";
                $("#uploaderFiles").append(html);
            }
        });
    }*/
</script>
<script>
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    var abattoir = getQueryString("abattoir");
    var loading = false;  //状态标记
    var html = "<option selected='' value='0'>请选择</option>";
    var ti = actionDate();
    var check_id = Math.random().toString(36).substr(2);
    console.log("ti=========",ti);
    $("#time").val(ti);
    /**
     * 当前页面url
     * @type {string}
     */
    sign_URL = document.location.toString();

    /**
     * 查询家禽种类
     */
    var list = [];
    $.ajax({
        type: "POST",
        url: "/shambles/mobile/booth/kind.do",
        data: {},
        success: function (data) {
            var html = "";
            if (data.code === 1) {
                list = data.response
                for (var i = 0; i < list.length; i++) {
                    html += "<div class='weui-cells weui-cells_checkbox'>" +
                        " <div class='name1'>" +
                        " <label class='weui-cell weui-check__label' for='s1" + i + "'" +
                        "onclick=checked('i" + i + "') >" +
                        " <div class='weui-cell__hd'>" +
                        " <input name='checkbox1' class='weui-check' id='i" + i + "'" +
                        " type='checkbox' value='i" + i + "'><i" +
                        " class='weui-icon-checked'></i>" +
                        " </div>" +
                        " <div class='weui-cell__bd'>" +
                        " <p name='i" + i + "'>" + list[i] + "</p>" +
                        " </div>" +
                        " </label>" +
                        " </div>" +
                        " <div class='name2'>" +
                        " <input class='weui-input' id='iii" + i + "' type='number' placeholder='数量'>" +
                        " </div>" +
                        " </div>"
                }
                $("#libiao").append(html)
            }
        }
    });
    $.ajax({
        url: "../../wechat/sign.do",
        data: {
            campusId: 1,
            url: sign_URL
        },
        async: false,
        type: "GET",
        success: function (data) {
            var ticket = data;
            /*
           * 此处需要两次执行相同的函数，否则返回ture时不能执行以下函数
           */
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: ticket.appId,
                timestamp: ticket.timestamp,
                nonceStr: ticket.nonceStr,
                signature: ticket.signature,
                jsApiList: ['checkJsApi', 'onMenuShareTimeline',
                    'onMenuShareAppMessage', 'onMenuShareQQ',
                    'onMenuShareWeibo', 'hideMenuItems',
                    'showMenuItems', 'hideAllNonBaseMenuItem',
                    'showAllNonBaseMenuItem', 'translateVoice',
                    'startRecord', 'stopRecord', 'onRecordEnd',
                    'playVoice', 'pauseVoice', 'stopVoice',
                    'uploadVoice', 'downloadVoice', 'chooseImage',
                    'previewImage', 'uploadImage', 'downloadImage',
                    'getNetworkType', 'openLocation', 'getLocation',
                    'hideOptionMenu', 'showOptionMenu', 'closeWindow',
                    'scanQRCode', 'chooseWXPay',
                    'openProductSpecificView', 'addCard', 'chooseCard',
                    'openCard']
            });
            var images = {
                localId: [],
                serverId: []
            };
            var imagename = "检疫证明";
            document.querySelector('#showPicker').onclick = function () {
                upImage(imagename);
            };

            function upImage(imagename) {
                wx.chooseImage({
                    success: function (res) {
                        images.localId = res.localIds;
                        console.log('已选择 ' + res.localIds.length + ' 张图片');

                        var i = 0;
                        var length = images.localId.length;
                        images.serverId = [];

                        function upload(imagename) {
                            wx.uploadImage({
                                localId: images.localId[i].toString(),
                                isShowProgressTips: images.localId[i].toString(),
                                success: function (res) {
                                    i++;
                                    console.log('已上传：' + i + '/' + length);
                                    //返回图片的服务器端ID res.serverId,然后调用wxImgCallback函数进行下载图片操作
                                    wxImgCallback(check_id, imagename, res.serverId);
                                    //   images.serverId.push(res.serverId);
                                    if (i < length) {
                                        upload(imagename);
                                    }
                                },
                                fail: function (res) {
                                    console.log(res);
                                }
                            });
                        }
                        upload(imagename);
                    }
                });
            }
        }
    })

    function wxImgCallback(check_id, imagename, serverId) {
        console.log("serverId=" + serverId);
        //将serverId传给wx_upload.php的upload方法
        var url = "/shambles/mobile/file/upload.do";
        $.get(url, {
            campusId: 1,
            imagename: imagename,
            serverId: serverId,
            id: check_id,
            classType: ""
        }, function (data) {
            console.log(data);
            if (data === 0) {
                alert("上传图片失败!");
                console.log(data.msg);
            } else if (data === 1) {
                //存储到服务器成功后的处理
                //存储到服务器成功后的处理
                findimagedata(check_id);
            }
        });
    }

    /**
     * 查询上传的检疫图片
     * */
    function findimagedata(check_id) {

        //存储到服务器成功后的处理
        //
        $.get("/shambles/mobile/booth/findSimple.do", {
            check_id: check_id
        }, function (data) {
            var code = data.code;
            if(code===1){
                var imgs = data.response;
                if(imgs.length>0){
                    $("#uploaderFiles").empty();
                    for (var i = 0;i < imgs.length; i++) {
                        var uri = imgs[i];
                        var src = DOMAIN + uri;
                        var photohtml = '<div class="weui-cell weui-cell_swiped" id="chilePhoto">' +
                            '<div class="weui-cell__bd">' +
                            '<div class="weui-cell">' +
                            '<div class="weui-cell__hd"><img src="' + src + '" alt="" style="width:60px;height:60px;margin-right:5px;display:block"></div>' +
                            '<div class="weui-cell__bd"><p></p></div>' +
                            '<div class="weui-cell__ft"</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="weui-cell__ft">' +
                            '</div>' +
                            '</div>';
                        $("#uploaderFiles").append(photohtml);
                    }

                }
            }
        });
    }

    /**
     * 查询预约时间是否冲突
     */
    function selectTime() {
        var time = $("#time").val();
        var timee = $("#select1").val();
        time = time + " " + timee;
        $.ajax({
            type: "POST",
            url: "/shambles/mobile/booth/subscribe.do",
            data: {
                "time": time,
                "id": 1
            },
            dataType: "json",
            error: function (request) {
                console.log(request);
                $(".weui-loadmore").hide();
                html += "网络连接故障";
                $("#ul").append(html);
            },
            success: function (data) {
                if (data.code != 1) {
                    $.alert("预约时间冲突！！", "失败", function () {
                        //点击确认后的回调函数
                        history.go(0)
                    });
                }
            }
        })
    }

    //获取选中类型
    function checked(val) {
        console.log(val);
        console.log($('#' + val).prop("checked"));
        var isChecked = $('#' + val).prop("checked");
        if (isChecked === false) {
            var boxes = document.getElementById(val);
            document.getElementsByName(val)[0].style.color = ' #CC0000';
            boxes.checked = true;
        } else {
            var boxes = document.getElementById(val);
            document.getElementsByName(val)[0].style.color = '#000000';
            boxes.checked = false;
        }
    }

    /**
     * 进行预约
     */
    $("#subscribe").click(function () {

        var detailDTOS = [];
        $("input[name='checkbox1']").each(function (i, dom) {
            // console.log('1111111',$(this).val());
            // console.log($(this).prop('checked'));
            if ($(this).prop('checked')) {
                var value = $(this).val();
                var ij = value.substring(1, 2);
                //类型
                var ty = list[ij];
                //对应的类型的数量
                var size = $("#iii" + ij).val();
                if (!size > 0 || size === "") {
                    $.alert("请输入数量", function () {
                    });
                    return;
                } else {
                    console.log("ty=====" + ty);
                    console.log("size=====" + size);
                    var detailDTO = new Object();
                    detailDTO.ty = ty;
                    detailDTO.size = size;
                    console.log("detailDTO====" + detailDTO.ty);
                    detailDTOS.push(detailDTO);
                }
            }
        });
        var time = $("#time").val();
        var timee = $("#select1").val();
        time = time + " " + timee;
        console.log("timee====",timee);
        if (time === null || time === "") {
            $.alert("请选择时间", function () {
            });
        } else if (!detailDTOS.length > 0) {
            $.alert("请选择类型与数量", function () {
            });
        } else {
            tijiao(detailDTOS, time)
        }

    });
    function tijiao(detailDTOS, time) {
        $.showLoading();
        $.ajax({
            type: "POST",
            url: "/shambles/mobile/booth/insertSub.do",
            data: {
                "time": time,
                "check_id":check_id,
                "detailDTOS": JSON.stringify(detailDTOS)
            },
            // dataType: "json",
            error: function (request) {
                console.log(request);
                $(".weui-loadmore").hide();
                html += "网络连接故障";
                $("#ul").append(html);
            }, success: function (data) {
                // setTimeout(function() {
                    $.hideLoading();
                    var code = data.code;
                    if (code === 1) {
                        $.alert("你的预约申请已提交，请等待", function () {
                            window.location.href = "index.html"
                        });
                    } else {
                        $.alert("预约失败", function () {
                            window.location.href = "index.html"
                        });
                    }
                // }, 1000);
            }
        })
    }

    function actionTime(value) {
        var date = new Date(value);
        Y = date.getFullYear() + '-';
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        D = date.getDate() + ' ';
        h = date.getHours() + ':';
        m = date.getMinutes() + ':';
        s = date.getSeconds();
        return Y + M + D + h + m + s;
    }

    function actionDate() {
        var date = new Date();
        Y = date.getFullYear() + '-';
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        D = date.getDate();
        if (D <= 9) {
            D = '0' + D;
        }
        return Y + M + D;
    }
</script>

</html>